<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="账套" prop="accountId">
        <el-select 
          v-model="queryParams.accountId" 
          placeholder="请选择账套"
          clearable
          @change="handleQuery"
          style="width: 100px;"
        >
          <el-option 
            v-for="item in accountOptions"
            :key="item.accountId"
            :label="item.accountName"
            :value="item.accountId"
          />
        </el-select>
      </el-form-item>
      
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['caiwu:voucher:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['caiwu:voucher:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['caiwu:voucher:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['caiwu:voucher:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['caiwu:voucher:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="voucherList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="凭证id" align="center" prop="voucherId" />
      <el-table-column label="凭证编号" align="center" prop="voucherNumber" />
      <el-table-column label="凭证日期" align="center" prop="voucherDate" >
        <template #default="scope">
          <span>{{ parseTime(scope.row.voucherDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="凭证摘要" align="center" prop="summary" />
            <el-table-column label="审核状态" align="center" prop="state" >
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.state==1">已审核</el-tag>
                <el-tag type="danger" v-else>未审核</el-tag>
              </template>
            </el-table-column>

      <el-table-column label="红冲状态" align="center" prop="status" >
        <template #default="scope">
          <!-- 通过盖章显示是否红冲 -->
             <div style="display: flex; align-items: center; justify-content: center; gap: 4px;">
        <el-icon v-if="scope.row.status === 1"  size="20" color="red">
                   <Printer />
                  </el-icon>
                  <el-icon v-else size="20"  color="green">
                    <Printer />
                  </el-icon>
                  <span v-if="scope.row.status === 1" style="color: red;">以红冲</span>
                  <span v-else style="color: green;">未红冲</span>
          </div>
         
        </template>
      </el-table-column>
      <el-table-column label="制单人 " align="center" prop="preparerId" />
      <el-table-column label="审核人" align="center" prop="remark" />
      <el-table-column label="过账人" align="center" prop="posterId" />
      <el-table-column label="借方金额" align="center" prop="debitAmount" />
      <el-table-column label="贷方金额" align="center" prop="creditAmount" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['caiwu:voucher:edit']" v-if="scope.row.state==0">红冲</el-button>
          <el-button link type="primary" icon="Edit" @click="handleAudit(scope.row)" v-hasPermi="['caiwu:voucher:edit']" v-if="scope.row.status==0">审核</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['caiwu:voucher:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改凭证管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="voucherRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="凭证编号" prop="voucherNumber">
          <el-input v-model="form.voucherNumber" placeholder="请输入凭证编号" />
        </el-form-item>
        <el-form-item label="凭证日期" prop="voucherDate">
          <el-date-picker clearable
            v-model="form.voucherDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择凭证日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="凭证摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="制单人 " prop="preparerId">
          <el-input v-model="form.preparerId" placeholder="请输入制单人 " />
        </el-form-item>
        <el-form-item label="审核人" prop="reviewerId">
          <el-input v-model="form.reviewerId" placeholder="请输入审核人" />
        </el-form-item>
        <el-form-item label="过账人" prop="posterId">
          <el-input v-model="form.posterId" placeholder="请输入过账人" />
        </el-form-item>
        <el-form-item label="借方金额" prop="debitAmount">
          <el-input v-model="form.debitAmount" placeholder="请输入借方金额" />
        </el-form-item>
        <el-form-item label="贷方金额" prop="creditAmount">
          <el-input v-model="form.creditAmount" placeholder="请输入贷方金额" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createdAt">
          <el-date-picker clearable
            v-model="form.createdAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择创建时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedAt">
          <el-date-picker clearable
            v-model="form.updatedAt"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Voucher">
import { listVoucher, getVoucher, delVoucher, addVoucher, updateVoucher, auditVoucher,getAccounts } from "@/api/caiwu/voucher";
import { ElMessageBox } from "element-plus";
import { getToken } from "@/utils/auth";
import { UploadFilled } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance();

const voucherList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: 1,
  },
  rules: {
    voucherNumber: [
      { required: true, message: "凭证编号不能为空", trigger: "blur" }
    ],
    voucherDate: [
      { required: true, message: "凭证日期不能为空", trigger: "blur" }
    ],
    accountId: [
      { required: true, message: "关联的账套id不能为空", trigger: "blur" }
    ],
  }
});
const { queryParams, form, rules  } = toRefs(data);

// 添加账套选项数据
const accountOptions = ref([]);

// 获取账套列表
function getAccountList() {
  getAccounts().then(response => {
    accountOptions.value = response;
    handleQuery();
  });
}



/** 查询凭证管理列表 */
function getList() {
  loading.value = true;
  listVoucher(queryParams.value).then(response => {
    voucherList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    voucherId: null,
    voucherNumber: null,
    voucherDate: null,
    accountId: null,
    summary: null,
    status: null,
    preparerId: null,
    reviewerId: null,
    posterId: null,
    debitAmount: null,
    creditAmount: null,
    createdAt: null,
    updatedAt: null
  };
  proxy.resetForm("voucherRef");
}

/** 搜索按钮操作 */

  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }





// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.voucherId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  form.value.accountId=queryParams.value.accountId 
  open.value = true;
  title.value = "添加凭证管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  if(row.status === 1){
    ElMessageBox.confirm('改数据以红冲"' + row.voucherNumber + '"是否确认红冲').then(function() {
          reset();
            const _voucherId = row.voucherId || ids.value
            getVoucher(_voucherId).then(response => {
              form.value = response.data;
              open.value = true;
            });
      })
      return;
    }
      reset();
        const _voucherId = row.voucherId || ids.value
        getVoucher(_voucherId).then(response => {
          form.value = response.data;
          open.value = true;
        });
  }

  function handleAudit(row){
    auditVoucher(row.voucherId).then(response => {
      proxy.$modal.msgSuccess("审核成功");
      getList();
    });
  }
  
/** 提交按钮 */
function submitForm() {
  proxy.$refs["voucherRef"].validate(valid => {
    if (valid) {
      if (form.value.voucherId != null) {
        updateVoucher(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addVoucher(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _voucherIds = row.voucherId || ids.value;
  proxy.$modal.confirm('是否确认删除凭证管理编号为"' + _voucherIds + '"的数据项？').then(function() {
    return delVoucher(_voucherIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('caiwu/voucher/export', {
    ...queryParams.value
  }, `voucher_${new Date().getTime()}.xlsx`)
}

// 上传参数
const upload = reactive({
  // 是否显示弹出层
  open: false,
  // 弹出层标题
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的数据
  updateSupport: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/caiwu/voucher/import"
});

// 文件上传中处理
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

// 文件上传成功处理
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  uploadRef.value.clearFiles();
  proxy.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
  getList();
};

// 提交上传文件
const uploadRef = ref();
function submitFileForm() {
  uploadRef.value.submit();
}

// 导入按钮操作
function handleImport() {
  upload.title = "凭证导入";
  upload.open = true;
}

// 下载模板操作
function importTemplate() {
  proxy.download('caiwu/voucher/importTemplate', {
  }, `voucher_template_${new Date().getTime()}.xlsx`);
}

getAccountList();
getList();

</script>
